let query = require('../../db/index');
// 用这个包来生成 Token 字符串
let jwt = require('jsonwebtoken');
let config = require('../../jwtSecretKey')
exports.login = async (req, res) => {
    console.log(req.body);
    try {
        let sql = "SELECT * FROM `admin`";
        let result = await query(sql);
        if (result && result.length > 0) {
            const user = result[0]; // 假设只有一条符合条件的用户信息
            console.log(user);
            if (user.account === req.body.account && user.password === req.body.password) {
                // 登录成功
                console.log('登录成功');
                // 生成token
                const resUser = { ...result[0], password: '', avatar: '' }
                const token = jwt.sign(resUser, config.jwtSecretKey, { expiresIn: config.jwtExpiresIn });
                res.dispatch(200, 'OK', { token: 'Bearer ' + token });
            } else {
                // 账号或密码不匹配
                console.log('账号或密码不正确');
                res.dispatch(401, 'Unauthorized', null);
            }
        } else {
            // 用户不存在
            console.log('用户不存在');
            res.dispatch(404, 'Not Found', null);
        }
    } catch (err) {
        // 查询出错
        console.error(err);
        res.dispatch(500, 'Internal Server Error', null);
    }
};
